package com.mewp.permissions.system.config;

import com.mewp.permissions.system.filter.TokenAuthenticationFilter;
import com.mewp.permissions.system.filter.TokenLoginFilter;
import com.mewp.permissions.system.service.AsyncLoginLogService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Security配置文件
 *
 * @author mewp
 * @version 1.0
 * @date 2023/7/30 23:57
 */
@Configuration
@EnableWebSecurity    // 添加 security 过滤器
@EnableGlobalMethodSecurity(prePostEnabled = true)    // 启用方法级别的权限认证
public class WebSecurityConfig {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private AuthenticationConfiguration authenticationConfiguration;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private AsyncLoginLogService asyncLoginLogService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 这是配置的关键，决定哪些接口开启防护，哪些接口绕过防护
        http
                //关闭csrf
                .csrf().disable()
                //禁用basic明文验证
                .httpBasic().disable()
                //禁用默认登录页
                .formLogin().disable()
                // 开启跨域以便前端调用接口
                .cors()
                .and()
                .authorizeHttpRequests(authorizationRequest ->
                        authorizationRequest
                                //允许所有的OPTIONS请求
                                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                                //允许直接访问授权登录接口
                                .antMatchers("/admin/system/index/login").permitAll()
                                //允许 默认的错误地址访问
                                .antMatchers("/error").permitAll()
                                //其他请求需要鉴权认证
                                .anyRequest().authenticated())
                //TokenAuthenticationFilter放到UsernamePasswordAuthenticationFilter的前面，这样做就是为了除了登录的时候去查询数据库外，其他时候都用token进行认证。
                .addFilterBefore(new TokenAuthenticationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class)
                .addFilter(new TokenLoginFilter(authenticationManager(authenticationConfiguration), redisTemplate, asyncLoginLogService))
                .userDetailsService(userDetailsService);

        //禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }

    /**
     * 获取AuthenticationManager（认证管理器），登录时认证使用
     *
     * @param authenticationConfiguration 身份认证配置
     * @return 认证管理器
     * @throws Exception 异常
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 密码明文加密方式配置
     *
     * @return BCrypt加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置某些接口直接不进入过滤链
     *
     * @return 自定义WebSecurity的回调
     */
    @Bean
    public WebSecurityCustomizer ignoringCustomizer() {
        return (web) -> web.ignoring().antMatchers(ignorePaths());
    }

    /**
     * 配置静态资源放行
     *
     * @return 字符串列表
     */
    public String[] ignorePaths() {
        return new String[]{
                "/favicon.ico",
                //排除swagger相关请求
                "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html"
        };
    }
}
